<?php
/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/8/28
 * Time: 14:22
 */
/**
 * Class SensorsData 神策数据上报
 */
namespace app\common\service;

use app\common\model\activity\InviteUserModel;
use app\common\model\article\PublishArticleModel;
use app\common\model\coin\CoinRuntimeModel;
use app\common\model\pair\PairRuntimeModel;
use app\common\model\pushlog\JpushArriveUpSensorsModel;
use app\common\model\pushlog\PushUpSensorsDataUserModel;
use app\common\model\user\UserBaseModel;
use app\common\model\user\UserDevicesModel;
use app\common\model\user\UserPairModel;
use app\common\redis\RedisModel;
use BatchConsumer;
use SensorsAnalytics;

require_once WEB_COMPOSER.'sensorsdata/sa-sdk-php/SensorsAnalytics.php';

class SensorsData
{
    public $sa;

    // 登录操作上报
    const LOGIN_REPORT = 'login';
    // 注册上报
    const REGISTER_REPORT = 'register';
    // 设置基本信息上报
    const SET_INFO_REPORT = 'set_info';
    // 更改设备
    const DEVICES_UPDATE_REPORT = 'devices_update';
    // 绑定、解绑
    const BIND_REPORT = 'bind';
    // 用户持仓上报
    const USER_COIN = 'user_coin';

    public function __construct( $channel = '')
    {
        # 从神策分析配置页面中获取的数据接收的 URL
        $SA_SERVER_URL = C( 'sensors_url' );
        if ( $channel == 'preview'){
            $SA_SERVER_URL = C( 'sensors_url_preview' );
        }

        # 可选参数，当缓存的数据量达到参数值时，批量发送数据
        $SA_BULK_SIZE = 100;
        # 可选参数，发送数据的超时时间，单位毫秒
        $SA_REQUEST_TIMEOUT = 100000;

        # 初始化一个 Consumer，用于数据发送
        # BatchConsumer 是同步发送数据，因此不要在任何线上的服务中使用此 Consumer
        $consumer = new BatchConsumer($SA_SERVER_URL, $SA_BULK_SIZE, $SA_REQUEST_TIMEOUT);
        # 初始化一个 Consumer，用于数据发送
        # BatchConsumer 是同步发送数据，因此不要在任何线上的服务中使用此 Consumer
//        $consumer = new DebugConsumer($SA_SERVER_URL ,True );
        # 使用 Consumer 来构造 SensorsAnalytics 对象

        $this->sa = new SensorsAnalytics($consumer);
    }

    /**
     * 用户登录上报数据
     */
    public function login( $user_id )
    {

    }

    /**
     * 用户注册上报数据
     */
    public function register( $user_id )
    {
        $data = array(

        );

        // 获取用户基本信息上报
        $userModel = UserBaseModel::getInstance();
        $user_info = $userModel->get_data_by_id( $user_id );

        if ( !$user_info ){
            return $data;
        }

        // 注册时间
        $data['create_time'] = $user_info['create_time'];
        
        // 手机号
        $data['mobile'] = $user_info['mobile'];

        // 微信标识
        $data['union_id'] = $user_info['union_id'];
        $data['display_rf_color'] = $user_info['display_rf_color'] == 1 ? "greenRise" : "redRise";
        $data['display_currency'] = $user_info['display_currency'] == 1 ? "USD" : "CNY";

        $inviteUserModel = InviteUserModel::getInstance();
        $inviteUserData = $inviteUserModel->where( array('user_id' => $user_id ) )->find();

        $data['parent_id'] = 0;
        if ( $inviteUserData ){
            $data['parent_id'] = (int)$inviteUserData['invite_user_id'];
        }

        $userDevicesModel = UserDevicesModel::getInstance();
        $userDevicesData = $userDevicesModel->get_data_by_unique_key( 'user_id', $user_id );
        if ( $userDevicesData ){
            // 查询设备信息
            $data['type'] = $userDevicesData['type'];
            $data['sensor_id'] = $userDevicesData['sensor_id'];
            $data['client_sn'] = $userDevicesData['client_sn'];
            // 神策未登录和已登录绑定
//            $this->sa->track_signup( $user_id, $data['sensor_id'] );
        }

        // 设备类型
        $data['register_type'] = $user_info['register_type'];
        return $data;
    }

    /**
     * 上报用户持仓数据
     */
    public function user_coin()
    {
        $py = PythonApiService::getInstance();
        $data_list = $py->user_coin_all();
        $redisModel = new RedisModel();

        // 获取上次缓存的用户持仓数据
        $cache_user_coin_list = $redisModel->get( 'str:sensors_data_user_coin');
        $cache_user_coin_list = $cache_user_coin_list ? : array();

        foreach ( $data_list as $key => $value ){
            $data = array();

            if ( !isset( $cache_user_coin_list[$key] ) || !array_diff( $cache_user_coin_list[$key]['exchange'], $value['exchange'] ) ){
                $data['walletPorfolioTokenID'] = $value['exchange'];
            }

            if ( !isset( $cache_user_coin_list[$key] ) || !array_diff( $cache_user_coin_list[$key]['manual'], $value['manual'] ) ){
                $data['handwrittenPorfolioTokenID'] = $value['manual'];
            }

            if ( !isset( $cache_user_coin_list[$key] ) || !array_diff( $cache_user_coin_list[$key]['chain'], $value['chain'] ) ){
                $data['apiKeyPorfolioTokenID'] = $value['chain'];
            }

            if ( $data ){
                $data['isPortfolioHolded'] = 1;
                $this->sa->profile_set( $key, true, $data );
            }
        }
        $redisModel->set( json_encode( $data_list ), 'str:sensors_data_user_coin' );
    }

    /**
     * 每天零点上报用户自选数据
     */
    public function user_pair()
    {
        // 获取当前所有的用户
        $userBaseModel = UserBaseModel::getInstance();
        $user_id_list = $userBaseModel->search_id_list_no_page();

        // 获取当前所有的交易对信息
        $UserPairModel = UserPairModel::getInstance();

        $where = array(
            'deleted' => -1,
            'status'  => 1
        );

        $user_pair_list = $UserPairModel->field( 'id,pair_id,user_id')->where( $where )->select();
        $user_pair_list = $user_pair_list ?: [];
        $pair_id_list = array_column( $user_pair_list, 'pair_id' );

        // 获取交易对信息
        $PairRuntimeModel = PairRuntimeModel::getInstance();
        $where = array(
            'id' => array( 'in', $pair_id_list)
        );

        $pair_list = $PairRuntimeModel->where( $where )->column( 'id,exchange,pair_name,symbol');
        $coin_list = array();
        $exchange_list = array();

        foreach ( $user_pair_list as $value ){
            $pair_info = $pair_list[$value['pair_id']];
            if ( $pair_info['exchange'] == 'global' ){
                if ( !isset( $coin_list[$value['user_id']] ) ){
                    $coin_list[$value['user_id']] = array();
                }

                $coin_list[$value['user_id']][] = $pair_info['symbol'];
            } else {

                if ( !isset( $exchange_list[$value['user_id']] ) ){
                    $exchange_list[$value['user_id']] = array();
                }
                $exchange_list[$value['user_id']][] = "{$pair_info['symbol']}/{$pair_info['pair_name']}";
            }
        }

        var_dump( $coin_list );
        var_dump( $exchange_list );

        foreach ( $user_id_list as $value ){
            $data = array(
                'WatchlistTokenID' => isset( $coin_list[$value] ) ? $coin_list[$value] : array(),
                'WatchlistBaseQuote' => isset( $exchange_list[$value] ) ? $exchange_list[$value] : array(),
            );

            $this->sa->profile_set( $value, true, $data );
            echo $value.'成功'.PHP_EOL;
        }
    }


    /**
     * 上报个推统计数据
     */
    public function up_getui_count()
    {
        // 获取未统计上报的push
        $jPushArticleModel = JpushArriveUpSensorsModel::getInstance();
        if ( ENV == 'test'){
            $time = date('Y-m-d H:i:s', time() - 300 );   // 获取十二个小时前的文章统计
        }else {
            $time = date('Y-m-d H:i:s', time() - 43200 );   // 获取十二个小时前的文章统计
        }
        
        $where = array(
            'create_time'       => array( 'LT', $time ),
            'is_up'           => 0
        );

        $push_list = $jPushArticleModel->where( $where )->select();
        $publishArticleModel = PublishArticleModel::getInstance();

        $pushUpSensorsDataUserModel = PushUpSensorsDataUserModel::getInstance();
        $coinRuntimeModel = CoinRuntimeModel::getInstance();
        $token_data_list = $coinRuntimeModel->get_key_value( 'id', 'symbol' );
        foreach ( $push_list as $value ){
            $update = array(
                'is_up'    => 1
            );

            // 获取有回执
            $article_data  = $publishArticleModel->get_data_by_id( $value['article_id'], true, true, false );

            // 获取token_list
            $symbol_list = array();

            if ( $value['coin_id'] ){
                $coin_id_list = json_decode( $value['coin_id'],true );
                if ( is_array( $coin_id_list ) ){
                    $token_id_list = $coin_id_list;
                    foreach ( $token_id_list as $coin_id ){
                        $symbol_list[] = $token_data_list[$coin_id];
                    }
                    $symbol_list=  implode( ",", $symbol_list );
                    $token_id_list=  implode( ",", $token_id_list );
                } else {
                    $token_id_list = $value['coin_id'];
                    $symbol_list = $token_data_list[$value['coin_id']];
                }
            } else {
                $symbol_list = "";
                $token_id_list = "";
            }

            $jPushArticleModel->update_data( $value['id'], $update );

            // 在线ios到达
            $GetuiiOSRecievedOnlineNO = 0;
            // 在线ios展示
            $GetuiiOSDisplayedOnlineNO = 0;
            // 在线ios点击
            $GetuiiOSClickedOnlineNO = 0;
            // 离线ios展示
            $GetuiiOSDisplayedOffineNO = 0;
            // 离线ios点击
            $GetuiiOSClickedOffineNO = 0;

            // 在线安卓送达
            $GetuiAndroidRecievedOnlineNO = 0;
            // 在线安卓展示
            $GetuiAndroidDisplayedOnlineNO = 0;
            // 在线安卓点击
            $GetuiAndroidClickedOnlineNO = 0;

            // 小米发送
            $GetuiAndroidRecievedOfflineNOXiaomi = 0;
            // 小米点击
            $GetuiAndroidClickedOfflineNOXiaomi = 0;

            // 魅族发送
            $GetuiAndroidRecievedOfflineNOMeizu = 0;
            // 魅族点击
            $GetuiAndroidClickedOfflineNOMeizu = 0;

            // 华为发送
            $GetuiAndroidRecievedOfflineNOHuawei = 0;

            // 获取本次推送用户数据
            $where = array(
                'task_id' => $value['push_msg_id_list']
            );

            $user_push_list = $pushUpSensorsDataUserModel->where( $where )->select();

            foreach ( $user_push_list as $v ){

                // 数据总量统计
                if ( $v['os_type'] == 'ios' ){
                    if ( $v['tunnel'] == 'getui' ){
                        $GetuiiOSRecievedOnlineNO++;
                        if ( $v['display'] == 1 ){
                            $GetuiiOSDisplayedOnlineNO++;
                        }
                        if ( $v['click'] == 1 ){
                            $GetuiiOSClickedOnlineNO++;
                        }
                    } else {
                        if ( $v['display'] == 1 ){
                            $GetuiiOSDisplayedOffineNO++;
                        }
                        if ( $v['click'] == 1 ){
                            $GetuiiOSClickedOffineNO++;
                        }
                    }
                } else {
                    if ( $v['tunnel'] == 'getui' ){
                        $GetuiAndroidRecievedOnlineNO++;

                        if ( $v['display'] == 1 ){
                            $GetuiAndroidDisplayedOnlineNO++;
                        }
                        if ( $v['click'] == 1 ){
                            $GetuiAndroidClickedOnlineNO++;
                        }
                    } elseif (  $v['tunnel'] == 'xiaomi' ){
                        $GetuiAndroidRecievedOfflineNOXiaomi++;
                        if ( $v['click'] == 1 ){
                            $GetuiAndroidClickedOfflineNOXiaomi++;
                        }
                    } elseif ( $v['tunnel'] == 'meizu' ){
                        $GetuiAndroidRecievedOfflineNOMeizu++;
                        if ( $v['click'] == 1 ){
                            $GetuiAndroidClickedOfflineNOMeizu++;
                        }
                    } elseif ( $v['tunnel'] == 'huawei'){
                        $GetuiAndroidRecievedOfflineNOHuawei++;
                    }
                }

                // 上报用户数据
                $info = array(
                    'GetuiTaskID' => $v['task_id'],
                    'tokenName'   => $symbol_list,
                    'tokenID'     => $token_id_list,
                    'pushTime'    => $value['create_time'],
                    'pushMsgType' => $value['type'],
                    'PushType'    =>  ( empty( $value['coin_id'] ) && $value['type'] == JpushArriveUpSensorsModel::PUSH_TYPE_ARTICLE  ) ? 'all' : 'group',
                    'GetuiClientID' => $v['client_id'],
                    'GetuiClientIDType' => $v['os_type'],
                    'GetuiTunnel'       => $v['tunnel'],
                    'GetuiRecieved'     => true,
                    'GetuiRecievedTime' => $v['recieved_time'],
                    'GetuiDisplayed'    => $v['display'] == 1 ? true : false,
                    'GetuiDisplayedTime' => $v['display_time'],
                    'GetuiClicked'       => $v['click'] == 1 ?  true : false,
                    'GetuiClickTime' => $v['click_time'],
                );

                if ( $article_data ){
                    $info['articleID'] = $article_data['id'];
                    $info['articleTitle'] = $article_data['title'];
                    $info['articleType'] = isset( PublishArticleModel::$cms_type_list[$article_data['article_type']] ) ? PublishArticleModel::$cms_type_list[$article_data['article_type']] : '文章';
                }
                $this->sa->track( $v['user_id'], true,'sendPushMsgPersonal', $info );
            }

            $properties = array(
                // 发送总人数
                'followTokenPeopleNO' => $value['push_count_ios'] + $value['push_count_android'],
                'followTokenPeopleNOiOS' => $value['push_count_ios'],
                'followTokenPeopleNOandroid' => $value['push_count_android'],
                'GetuiTaskID' => $value['push_msg_id_list'],
                'pushMsgType' => $value['type'],
                'PushType'    => ( empty( $value['coin_id'] ) && $value['type'] == JpushArriveUpSensorsModel::PUSH_TYPE_ARTICLE  ) ? 'all' : 'group',
                'articleID' => $value['article_id'] ? $value['article_id'] : 0,
                'tokenName'   => $symbol_list,
                'tokenID'     => $token_id_list,
                'pushTime'     => $value['create_time'],
                'GetuiiOSRecievedOnlineNO' => $GetuiiOSRecievedOnlineNO,
                'GetuiiOSDisplayedOnlineNO' => $GetuiiOSDisplayedOnlineNO,
                'GetuiiOSClickedOnlineNO' => $GetuiiOSClickedOnlineNO,
                'GetuiiOSDisplayedOffineNO' => $GetuiiOSDisplayedOffineNO,
                'GetuiiOSClickedOffineNO' => $GetuiiOSClickedOffineNO,
                'GetuiAndroidRecievedOnlineNO' => $GetuiAndroidRecievedOnlineNO,
                'GetuiAndroidDisplayedOnlineNO' => $GetuiAndroidDisplayedOnlineNO,
                'GetuiAndroidClickedOnlineNO' => $GetuiAndroidClickedOnlineNO,
                'GetuiAndroidRecievedOfflineNOXiaomi' => $GetuiAndroidRecievedOfflineNOXiaomi,
                'GetuiAndroidClickedOfflineNOXiaomi' => $GetuiAndroidClickedOfflineNOXiaomi,
                'GetuiAndroidRecievedOfflineNOMeizu' => $GetuiAndroidRecievedOfflineNOMeizu,
                'GetuiAndroidClickedOfflineNOMeizu' => $GetuiAndroidClickedOfflineNOMeizu,
                'GetuiAndroidRecievedOfflineNOHuawei' => $GetuiAndroidRecievedOfflineNOHuawei,
            );

            if ( $article_data ){
                $properties['articleID'] = $article_data['id'];
                $properties['articleTitle'] = $article_data['title'];
                $properties['articleType'] = isset( PublishArticleModel::$cms_type_list[$article_data['article_type']] ) ? PublishArticleModel::$cms_type_list[$article_data['article_type']] : '文章';
            }


            $this->sa->track( 'jpush_article_count', true,'sendPushMsg', $properties );
        }

    }


    /**
     * 用户修改基本信息上报数据
     * @param $user_id
     * @return array
     */
    public function set_info( $user_id )
    {
        $data = array(

        );

        // 获取用户基本信息上报
        $userModel = UserBaseModel::getInstance();
        $user_info = $userModel->get_data_by_id( $user_id );

        if ( !$user_info ){
            return $data;
        }

        $data['display_rf_color'] = $user_info['display_rf_color'] == 1 ? "greenRise" : "redRise";
        $data['display_currency'] = $user_info['display_currency'] == 1 ? "USD" : "CNY";

        return $data;
    }

    /**
     * 用户设备信息有更新上报数据
     * @param $user_id
     * @return array
     */
    public function devices_update( $user_id )
    {
        $data = array();
        $userDevicesModel = UserDevicesModel::getInstance();
        $userDevicesData = $userDevicesModel->get_data_by_unique_key( 'user_id', $user_id );
        if ( $userDevicesData ){
            // 查询设备信息
            $data['type'] = $userDevicesData['type'];
            $data['sensor_id'] = $userDevicesData['sensor_id'];
            $data['client_sn'] = $userDevicesData['client_sn'];
        }

        return $data;

    }

    /**
     * 用户绑定、解绑操作上报信息
     * @param $user_id
     * @return array
     */
    public function bind( $user_id )
    {
        $data = array(

        );

        // 获取用户基本信息上报
        $userModel = UserBaseModel::getInstance();
        $user_info = $userModel->get_data_by_id( $user_id );

        if ( !$user_info ){
            return $data;
        }
        // 手机号
        $data['mobile'] = $user_info['mobile'];

        // 微信标识
        $data['union_id'] = $user_info['union_id'];
        return $data;
    }

    /**
     * 设置已登录用户属性
     * @param $user_id
     * @param array $data
     */
    public function profile_set( $user_id, array $data  )
    {
        if ( $data ){
            # 设置用户属性
            $this->sa->profile_set( $user_id, true, $data );
        }
        $this->sa->close();
    }

    /**
     * 上报数据
     * @param $data
     */
    public function set( $data )
    {
        $profile_data = array();
        if (  method_exists($this, $data['report_name']) ){
            $profile_data = $this->{$data['report_name']}( $data['user_id'] );
        }
        $this->profile_set( $data['user_id'], $profile_data );
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        $this->sa->close();
    }


}